package com.zhonghui.modules.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eshop.apiCode.EshopException;
import com.eshop.service.Impl.BaseServiceImpl;
import com.zhonghui.modules.domain.StoreProductRelation;
import com.zhonghui.modules.mapper.ProductRelationMapper;
import com.zhonghui.modules.service.ProductRelationService;
import com.zhonghui.modules.vo.StoreProductRelationQueryVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class ProductRelationServiceImpl extends BaseServiceImpl<ProductRelationMapper, StoreProductRelation> implements ProductRelationService {

    private final ProductRelationMapper relationMapper;

    @Override
    public Boolean shiFouCollect(long productId, long uid) {
        Integer count = relationMapper.selectCount(Wrappers.<StoreProductRelation>lambdaQuery()
                .eq(StoreProductRelation::getUid, uid)
                .eq(StoreProductRelation::getProductId, productId)
                .eq(StoreProductRelation::getType, "collect"));
        if (count > 0){
            return true;
        }
        return false;
    }

    @Override
    public void addCollect(long productId, long uid, String category) {
        if (shiFouCollect(productId,uid)){
            throw new EshopException("已收藏");
        }
        StoreProductRelation productRelation = StoreProductRelation.builder()
                .id(uid)
                .productId(productId)
                .type(category)
                .build();
        relationMapper.insert(productRelation);
    }

    @Override
    public void quXiaoCollect(long productId, long uid, String category) {
        StoreProductRelation storeProductRelation = this.lambdaQuery()
                .eq(StoreProductRelation::getProductId, productId)
                .eq(StoreProductRelation::getUid, uid)
                .eq(StoreProductRelation::getType, category)
                .one();
        if (storeProductRelation == null){
            throw new EshopException("已取消");
        }
        this.removeById(storeProductRelation.getId());
    }

    @Override
    public List<StoreProductRelationQueryVo> userCollectList(int page, int limit, Long uid, String type) {
        Page<StoreProductRelation> modelPage = new Page<>(page, limit);
        List<StoreProductRelationQueryVo> select = relationMapper.select(modelPage, uid, type);
        return select;
    }
}
